﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace EGN
{
    class EGNMethods
    {
        public static List<string> GetEGN(string fileName) 
        {
            List<string> result = new List<string>();
            StreamReader inputFile = new StreamReader(fileName);
            using (inputFile) 
            {
                string pattern = @"(\W|\A)(?<EGN>\d{10})(\D|\Z)";
                Regex check = new Regex(pattern);
                string line = inputFile.ReadLine();
                while (line!=null)
                {
                    Match match = check.Match(line);
                    while (match.Success)
                    {
                        result.Add(match.Groups["EGN"].ToString());
                        match = match.NextMatch();
                    }
                    line = inputFile.ReadLine();
                }
            }
            return result;
        }

        public static void PrintEGN(List<string> toPrint) 
        {
            foreach (var item in toPrint)
            {
                Console.WriteLine(item);
            }
        }

        public static void ReverseEgn(string fileName) 
        {
            StreamReader inputFile = new StreamReader(fileName);
            using (inputFile)
            {
                StringBuilder toWrite = new StringBuilder();
                string pattern = @"(\W|\A)(?<EGN>\d{10})(\D|\Z)";
                string line = inputFile.ReadLine();
                StreamWriter outputFile = new StreamWriter("fileName" + ".tmp");
                using (outputFile)
                {
                    while (line != null)
                    {
                        toWrite.Append(Regex.Replace(line, pattern, new MatchEvaluator(ReverseEGN)));
                        outputFile.WriteLine(toWrite);
                        toWrite.Clear();
                        line = inputFile.ReadLine();
                    }
                }
            }
            File.Copy("fileName" + ".tmp", fileName, true);
            File.Delete("fileName" + ".tmp");
        }

        static string ReverseEGN(Match match)
        {
            string result;
            string pattern = @"\d{10}";
            result = Regex.Replace(match.Value, pattern, new MatchEvaluator(ReverseNumbers));
            return result;
        }
        static string ReverseNumbers(Match match) 
        {
            string egn = match.Value;
            StringBuilder sb = new StringBuilder();
            for (int i = egn.Length-1; i >=0; i--)
            {
                sb.Append(egn[i]);
            }
            return sb.ToString();
        }
    }
}
